//
//  SISSPassengerResourceCooperationViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/4/13.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSPassengerResourceCooperationViewController.h"
#import "SISSComboBoxView.h"
#import "SISSRecommandPassengerCell.h"
#import "SISSCooperationDetailViewController.h"
#import "SISSEnrollPassengerDetailViewController.h"
#import "SISSPassengerResourceEnrollViewController.h"
#import "SISSJsonRequestNetworkingManager+Registration.h"
#import "SISSJsonRequestNetworkingManager+Resources.h"

static NSString *passengerCooperationCellReuseID = @"passengerCooperationCellReuseID";

@interface SISSPassengerResourceCooperationViewController ()<SISSComboBoxViewDelegate,UITableViewDelegate,UITableViewDataSource,SISSRecommandPassengerCellDelegate>

/** 房源数组 */
@property (strong, nonatomic) NSArray<SISSPassengerResourceModel *> *passengerResourceArr;
/** tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/** 筛选视图 */
@property (weak, nonatomic) SISSComboBoxView *filterView;
/* 下一步按钮 */
@property (weak, nonatomic) UIButton *nextStepButton;

/** 可见范围 */
@property (assign, nonatomic) NSInteger visibleRange;
/** 排序规则 */
@property (assign, nonatomic) NSInteger orderAttrs;
/** 区域 */
@property (copy, nonatomic) NSString *region;
/** 街道办 */
@property (copy, nonatomic) NSString *regionDetail;
/** 价格 */
@property (copy, nonatomic) NSString *price;
/** 户型 */
@property (copy, nonatomic) NSString *houseType;
/** 面积 */
@property (copy, nonatomic) NSArray *area;
/** 朝向 */
@property (copy, nonatomic) NSArray *direction;
/** 装修程度 */
@property (copy, nonatomic) NSArray *decoration;
/** pageNo */
@property (assign, nonatomic) NSInteger pageNo;

/* lastIndexPath */
@property (strong, nonatomic) NSIndexPath *lastIndexPath;
/* isSelect */
@property (assign, nonatomic) BOOL isSelect;

@end

@implementation SISSPassengerResourceCooperationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isSelect = NO;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"客源登记" style:UIBarButtonItemStylePlain target:self action:@selector(enrollClickAction)];
    [self.navigationItem.rightBarButtonItem setTintColor:COLOR(0x8998A5)];
    
    // 上下拉刷新
    __weak typeof(self) weakSelf = self;
    [[SISSRefresh sharedRefresh] prepareHeaderRefresh:self.tableView loadDataBlock:^{
        [weakSelf upDownLoadData];
    }];
//    [[SISSRefresh sharedRefresh] prepareFooterRefresh:self.tableView reloadDataBlock:^{
//        
//        [weakSelf reloadMoreData];
//    }];
}


/**
 返回按钮点击事件
 */
- (void)back {
    
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}


/**
 登记按钮点击事件
 */
- (void)enrollClickAction {
    
    SISSPassengerResourceEnrollViewController *vc = [[SISSPassengerResourceEnrollViewController alloc] init];
    vc.isRegistration = YES;
    vc.isCooperation = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self requestPassengerResourceData];
}

#pragma mark - SISSComboBoxViewDelegate
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"预算"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"户型"]) {
        self.houseType = title;
    }
    [self requestPassengerResourceData];
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    [self requestPassengerResourceData];
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {
    
    if ([title isEqualToString:@"可见范围"]) {
        self.visibleRange = 2;
    } else if ([title isEqualToString:@"面积"]) {
        self.area = @[];
        self.area = subtitles ;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = @[];
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = @[];
        self.decoration = subtitles;
    } 
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    [self requestPassengerResourceData];
    self.visibleRange = 1;
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}


#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [tableView tableViewDisplayWithMessage:@"没有找到相关合作..." ifNecessaryForRowCount:self.passengerResourceArr.count];
    return self.passengerResourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SISSRecommandPassengerCell *cell = [tableView dequeueReusableCellWithIdentifier:passengerCooperationCellReuseID forIndexPath:indexPath];
    
    cell.isChooseMain = YES;
    cell.delegate = self;
    cell.passengerResourceModel = self.passengerResourceArr[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SISSEnrollPassengerDetailViewController *vc = [[SISSEnrollPassengerDetailViewController alloc] init];
    vc.title = @"客源详情";
    vc.passengerModel = self.passengerResourceArr[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - SISSRecommandPassengerCellDelegate
- (BOOL)recommandPassengerCell:(SISSRecommandPassengerCell *)cell checkButtonIsSelected:(BOOL)isSelected {
    
    [self.nextStepButton setBackgroundColor: isSelected ? COLOR(0x349DC5) : COLOR(0x8998A5)];
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    self.passengerResourceArr[self.lastIndexPath.row].isSelected = NO;
    self.passengerResourceArr[indexPath.row].isSelected = isSelected;
    self.isSelect = isSelected;
    self.lastIndexPath = indexPath;
    
    [self.tableView reloadData];
    
    return NO;
}




#pragma mark - 下一步按钮点击事件
- (void)nextStepButtonClickAtion {
    
    if (!self.isSelect) return;
    
    if (self.isProgressEnter) {
        if (self.completeBlock) {
            self.completeBlock(self.passengerResourceArr[self.lastIndexPath.row]);
        }
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        
        SISSCooperationDetailViewController *vc = [[SISSCooperationDetailViewController alloc] init];
        vc.title = @"合作详情";
        self.isSelect = NO;
        vc.passengerModel = self.passengerResourceArr[self.lastIndexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownLoadData {
    
    //    self.pageNo = 0;
    [self requestPassengerResourceData];
}

- (void)reloadMoreData {
    
    //    self.pageNo += 1;
    [self.tableView.mj_footer endRefreshing];
    //    [self requestPassengerResourceData];
}

- (void)requestPassengerResourceData {
    
    // 非空处理
    NSString *region = self.region ? self.region : @"不限";
    NSString *regionDetail = self.regionDetail ? self.regionDetail : @"不限";
    NSString *price = self.price ? self.price : @"";
    NSString *houseType = self.houseType ? self.houseType : @"不限";
    
    NSDictionary *parameters = @{
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"region":region,
                                 @"regionDetail":regionDetail,
                                 @"price":price,
                                 @"houseType":houseType,
                                 @"area":self.area ,
                                 @"direction":self.direction,
                                 @"decoration":self.decoration
                                 };
    WeakSelf
    if (!self.isProgressEnter) {
        [kJsonRequestNetworkingManager requestPassengerCooperationWithparameters:parameters success:^(NSArray<SISSPassengerResourceModel *> *passengerResources) {
            
            //        if (self.passengerResourceArr.count != 0 && kSISSRefresh.refreshType == SISSRefressTypeUpDown) {
            //
            //            [self.passengerResourceArr removeAllObjects];
            //        }
            //        for (int i = 0; i < passengerResources.count; i++) {
            //
            //            [self.passengerResourceArr addObject:passengerResources[i]];
            //        }
            weakSelf.passengerResourceArr = passengerResources;
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [weakSelf.tableView reloadData];
                
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
            }];
            
        } failed:^(NSError *error) {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            NSLog(@"%@",error);
        }];
    } else {
        [kJsonRequestNetworkingManager requestEntrustPassengerResourceWithParameters:parameters success:^(NSArray<SISSPassengerResourceModel *> *passengerResources) {
            
            weakSelf.passengerResourceArr = passengerResources;
            
            // 回到主线程刷新UI
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [weakSelf.tableView reloadData];
                
                [weakSelf.tableView.mj_header endRefreshing];
                //            [weakSelf.tableView.mj_footer endRefreshing];
                //            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }];
            
        } failed:^(NSError *error) {
            [weakSelf.tableView.mj_header endRefreshing];
            //        [weakSelf.tableView.mj_footer endRefreshing];
            NSLog(@"%@",error);
        }];
    }
}


#pragma mark - 设置UI
- (void)setupSubviews {
    [super setupSubviews];
    
    // 添加筛选视图
    SISSComboBoxView *filterView = [[SISSComboBoxView alloc] initWithFrame:CGRectMake(0, NAVIGATION_HEIGHT, SCREEN_WIDTH, 44) isHouseResource:NO isCooperation:NO];
    filterView.delegate = self;
    [self.view addSubview:filterView];
    self.filterView = filterView;
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    // 自动行高
    tableView.estimatedRowHeight = 80;
    tableView.rowHeight = UITableViewAutomaticDimension;
    [tableView registerClass:[SISSRecommandPassengerCell class] forCellReuseIdentifier:passengerCooperationCellReuseID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    UIButton *nextStepButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextStepButton setTitle:@"下一步" forState:UIControlStateNormal];
    [nextStepButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextStepButton setBackgroundColor:COLOR(0x8998A5)];
    [nextStepButton addTarget:self action:@selector(nextStepButtonClickAtion) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextStepButton];
    self.nextStepButton = nextStepButton;
    
    // 自动布局
    WeakSelf
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.top.equalTo(filterView.mas_bottom);
        make.bottom.equalTo(nextStepButton.mas_top);
    }];
    
    [nextStepButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(49);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(weakSelf.view);
        }
    }];
}

#pragma mark - Getter & Setter

//- (NSMutableArray<SISSPassengerResourceModel *> *)passengerResourceArr {
//    if (!_passengerResourceArr) {
//        _passengerResourceArr = [NSMutableArray array];
//    }
//    return _passengerResourceArr;
//}


- (NSArray *)area {
    if (_area == nil) {
        _area = [NSArray array];
    }
    return _area;
}

- (NSArray *)direction {
    if (_direction == nil) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    if (_decoration == nil) {
        _decoration = [NSArray array];
    }
    return _decoration;
}

@end
